import Mod_bl as bl
import sys
import wx
from wx.xrc import *

res = XmlResource('gui.xrc')

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None, -1, u"Hello World")

        self.list = wx.ListCtrl(self, -1,
                                style=wx.LC_REPORT 
                                | wx.BORDER_NONE
                                | wx.LC_EDIT_LABELS
                                | wx.LC_SORT_ASCENDING
                                )

        self.list.InsertColumn(0, "Id")
        self.list.InsertColumn(1, "Artist")
        self.list.InsertColumn(2, "Title", wx.LIST_FORMAT_RIGHT)

        bRetrieve = wx.Button(self, -1, u"Retrieve")
        self.Bind(wx.EVT_BUTTON, self.OnRetrieve, bRetrieve)

        bInsert = wx.Button(self, -1, u"Insert")
        self.Bind(wx.EVT_BUTTON, self.OnInsert, bInsert)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.list, 1, wx.ALL | wx.EXPAND, 10)
        btnsizer = wx.StdDialogButtonSizer()
        btnsizer.Add(bRetrieve)
        btnsizer.Add(bInsert)
        btnsizer.Realize()
        sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        self.SetSizer(sizer)

    def OnRetrieve(self, evt):
        self.list.DeleteAllItems()
        for score in bl.Session().query(bl.scores_table):
            print score.id, score.author, score.title
            index = self.list.InsertStringItem(sys.maxint, unicode(score.id))
            self.list.SetStringItem(index, 1, score.author)
            self.list.SetStringItem(index, 2, score.title)
            self.list.SetItemData(index, score.id)

    def OnInsert(self, evt):
        dlg = res.LoadDialog(self, 'Score')
        dlg.FindWindowByName('ID_OK').SetId(wx.ID_OK)
        dlg.FindWindowByName('ID_CANCEL').SetId(wx.ID_CANCEL)
        #dlg = TestDialog(self, -1, "Sample Dialog")
        dlg.CenterOnScreen()

        # this does not return until the dialog is closed.
        val = dlg.ShowModal()
        itemNames = ['t_ID', 't_author', 't_title']
    
        if val == wx.ID_OK:
            result = tuple((dlg.FindWindowByName(name).GetValue()
                            for name in itemNames))
            print result
            i = bl.scores_table.insert()
            i.execute(author=result[1], title=result[2])
            print("You pressed OK")
        else:
            print("You pressed Cancel")

        dlg.Destroy()

class App(wx.App):
    def OnInit(self):
            frame = Frame()
            self.SetTopWindow(frame)

            print "Print statements go to this stdout window by default."

            frame.Show(True)
            return True
 
app = App(redirect=True,filename='ScoresArchiver.log')
app.MainLoop()
